const crypto = require('crypto');
const algorithm = 'aes-128-cbc';
const key = new Buffer('0102030405060708', 'binary')
const iv = new Buffer('0102030405060708', 'binary')
const CryptoJS = require("crypto-js");
const config = require('config')
const clientKey = config.get('clientKey')

function encrypt(text) {
    let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), Buffer.from(iv));
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return encrypted.toString('hex');
}

function decrypt(text) {
    let encryptedText = Buffer.from(text, 'hex');
    let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), Buffer.from(iv));
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
}

let decryptClient = (text) => {
    let decipher = CryptoJS.AES.decrypt(text, clientKey);
    decipher = decipher.toString(CryptoJS.enc.Utf8);
    if(!decipher){
        let error = new Error()
        error.status = 401
        error.message = '秘钥解码失败'
        throw error
    }
    return decipher;
}

const hash = (text)=>{
    return CryptoJS.SHA512(text).toString(CryptoJS.enc.Hex)
}

module.exports = {encrypt,decrypt,decryptClient,hash}

